using System;
using System.Text;
using System.Security;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace PowerShellService
{
    [WebService(Namespace = "http://scfcas/PowerShellService")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Service : System.Web.Services.WebService
    {
        [WebMethod]
        public string invoke(string script)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(script);

            StringBuilder builder = new StringBuilder();
            try
            {
                runspace.Open();
                foreach (PSObject obj in pipeline.Invoke())
                {
                    builder.AppendLine(obj.ToString());
                }
                return builder.ToString();
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                runspace.Dispose();
                pipeline.Dispose();
            }
        }
    }
}